// 对http 请求进行封装 过滤一些常见的错误 只返回响应成功的请求
import store from '@/store'
export default {
    'isPost': true,
    request(url,data,showLoading,isSinglePost) {
        var that = this;
        return new Promise(function (resolve, reject) {
            //单例方式  
            if (isSinglePost && that.isPost) {console.info('跳过'); reject({ 'message': '加载中' }); return; }
            else { that.isPost = true; }
            
            if(showLoading){ uni.showLoading({ title: '加载中..' }); }
            var app = getApp();
            // 包含协议头则直接请求 不拼接 根路径
            let all_url = app.globalData.publicUrl + url;
            if(url.indexOf('https')==0 || url.indexOf('http')==0){
                all_url = url
            }
            const extConfig = uni.getExtConfigSync ? uni.getExtConfigSync() : {}
            // data["appid"] = extConfig["extAppid"]
            // data["merchant_id"] = extConfig["merchantId"]
            var header ={'content-type': 'application/json'}
            if(store.state.token){
              header["token"] = store.state.token
            }
			// 开发时取消注释,可无需重复登录代替vuex
			// if(uni.getStorageSync('token')){
			//   header["token"] = uni.getStorageSync('token')
			// }
            uni.request({
                url: all_url,
                header,
                data,
                method: 'post',
                success(res) {
                    if (res.statusCode == 200) {
                        if (res.data.code == 20000) {
                            resolve(res.data);
                        }
                        else {
							resolve(res.data);
                            uni.showToast({ title: res.data.message, icon: 'none' })
                        }
                    }
                    else {
                        uni.showToast({ title: '响应错误', icon: 'none' });
                        reject({ 'message': '响应错误' })
                    }
                },
                fail(){
                    uni.showToast({ title: '网络错误', icon: 'none' })
                    reject({ 'message': '网络错误' })
                },
                complete() {
                    if(showLoading)
                    {
                        uni.hideLoading();
                    }
                    that.isPost = false;
                }
            })
        })
    }
}
